package com.hlkj.warboot.configurer.Intercept;


import com.alibaba.fastjson.JSONObject;
import com.hlkj.warboot.configurer.annotation.AuthToken;
import com.hlkj.warboot.configurer.util.JwtUtil;
import com.hlkj.warboot.module_sys.entity.AdminEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description Token拦截器
 * @Author lixing
 * @Date 2021/6/9 13:56
 */
@Component
@Slf4j
public class AuthTokenIntercept implements HandlerInterceptor {
    /**
     * @Description 前置拦截
     * @Author lixing
     * @Date 2021/6/9 13:58
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 获取注解对象
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        AuthToken authToken = handlerMethod.getMethodAnnotation(AuthToken.class);
        if (authToken != null) {
            // 获取注解中的参数
            boolean isCheck = authToken.isCheck();
            if (isCheck) {
                String token = request.getHeader("Authorization");
                if (StringUtils.isEmpty(token)) {
                    //throw new NeedLoginException("token不存在");
                }
                try {
                    JSONObject jsonObject = JwtUtil.verifyJwtForHS256(token);
                    // 创建登录用户
                    AdminEntity loginUserInfo = new AdminEntity();
                    loginUserInfo.setId(jsonObject.getString("id"));
                    request.setAttribute("loginUserInfo", loginUserInfo);
                } catch (Exception e) {
                    log.error("token已过期，请重新获取", e);
                    //throw new NeedLoginException("token失效");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
